package org.example.backend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.backend.domain.SysMenu;
import org.example.backend.service.SysMenuService;
import org.example.backend.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 28254
* @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
* @createDate 2024-10-10 23:25:11
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{
    @Autowired
    private SysMenuMapper sysMenuMapper;
    public List<SysMenu> findMenuTree(){
        List<SysMenu> menuList = sysMenuMapper.findMenuTree();
       return buildTree(menuList); // 返回处理好的数据
    }

    private List<SysMenu> buildTree(List<SysMenu> menus){
        Map<Integer, SysMenu> menuMap = new HashMap<>();
        List<SysMenu> rootMenus = new ArrayList<>();
        // 首先将所有菜单放入map中，方便后续查找
        for (SysMenu menu : menus) {
            menuMap.put(menu.getMenuId(), menu);
        }
        // 构建树形结构
        for (SysMenu menu : menus) {
            if (menu.getParentId() == null || !menuMap.containsKey(menu.getParentId())) {
                // 如果是根节点或者找不到父节点，则认为是根节点
                rootMenus.add(menu);
            } else {
                // 否则，找到其父节点，并将其添加到父节点的子节点列表中
                SysMenu parentMenu = menuMap.get(menu.getParentId());
                if (parentMenu.getChildren() == null) {
                    parentMenu.setChildren(new ArrayList<>());
                }
                parentMenu.getChildren().add(menu);
            }
        }
        return rootMenus;
    }
}




